package com.ebupt.migu.caller.service;

import com.alibaba.fastjson.JSON;
import com.ebupt.migu.caller.mapper.ScheduleMapper;
import com.ebupt.migu.common.sms.CallerHungUpMessageBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuyangyang@e-byte.com
 * @description: TODO
 * @date 2024/8/15 15:40
 */
@Slf4j
@Service
public class CallerHungUpMessageProducerService {
    @Autowired
    private ScheduleMapper mapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private final KafkaTemplate<String, CallerHungUpMessageBean> kafkaTemplate;

    @Autowired
    public CallerHungUpMessageProducerService(KafkaTemplate<String, CallerHungUpMessageBean> kafkaTemplate) {
        this.kafkaTemplate = kafkaTemplate;
    }

    public void sendMessage(CallerHungUpMessageBean bean) {
        kafkaTemplate.send("RFMENT-CALLER-HUNG-UP-MESSAGE-TOPIC", bean);
    }

    public void refreshMegaMarketConf() {
        List<HashMap<String, String>> confs = mapper.qryMegaMarketConf();
        for (HashMap<String, String> conf : confs) {
            conf = convertKeysToCamelCase(conf);
            String key = "mega-market-conf-" + String.valueOf(conf.get("id"));
            if (redisTemplate.hasKey(key)) {
                redisTemplate.delete(key);
            }
            log.info("大营销平台配置信息录入缓存：{}", conf);
            redisTemplate.opsForValue().set(key, JSON.toJSONString(conf));
        }
    }

    private HashMap<String, String> convertKeysToCamelCase(HashMap<String, String> conf) {
        HashMap<String, String> newConf = new HashMap<>();
        for (Map.Entry<String, String> entry : conf.entrySet()) {
            String newKey = convertToCamelCase(entry.getKey());
            newConf.put(newKey, entry.getValue());
        }
        return newConf;
    }

    private String convertToCamelCase(String s) {
        String[] parts = s.split("_");
        StringBuilder camelCase = new StringBuilder(parts[0]);
        for (int i = 1; i < parts.length; i++) {
            camelCase.append(parts[i].substring(0, 1).toUpperCase()).append(parts[i].substring(1));
        }
        return camelCase.toString();
    }
}
